import React, { useCallback } from 'react';
import { BottomSheetFlashList, BottomSheetModal } from '@gorhom/bottom-sheet';
import { TouchableOpacity, View } from 'react-native';
import { Icon, useAppTheme } from 'tsun-smart-ui';
import CustomBottomSheetBackdrop from './CustomBottomSheetBackdrop';
import { Text } from 'react-native';

type SingleSelectBottomSheetProps<T = any> = {
  title: string;
  options: string[] | T[];
  selectedIndex: number;
  onSelect: (index: number) => void;
  labelKey?: keyof T;
};

const SingleSelectBottomSheet = React.forwardRef<
  BottomSheetModal,
  SingleSelectBottomSheetProps
>((props, ref) => {
  const appTheme = useAppTheme();

  const renderItem = useCallback(
    ({ item, index }: { item: string | any; index: number }) => {
      const isSelected = props.selectedIndex === index;
      const color = isSelected ? 'text-brand1' : 'text-text1';

      const displayText = props.labelKey
        ? (item as any)[props.labelKey]
        : (item as string);

      return (
        <TouchableOpacity
          className="flex-row items-center justify-between px-4 py-3 h-12"
          onPress={() => {
            props.onSelect(index);
            setTimeout(() => {
              // @ts-ignore
              ref?.current?.close();
            }, 400);
          }}
        >
          <Text className={`font-normal text-[16px] ${color}`}>
            {displayText}
          </Text>
          {isSelected && (
            <Icon
              name="check"
              size={20}
              color={appTheme.colors?.brand?.primary}
            />
          )}
        </TouchableOpacity>
      );
    },
    [props.options, props.selectedIndex]
  );

  return (
    <BottomSheetModal
      ref={ref}
      snapPoints={['50%']}
      enablePanDownToClose
      enableDynamicSizing={false}
      backdropComponent={CustomBottomSheetBackdrop}
      handleStyle={{
        backgroundColor: appTheme.colors?.background?.disabled,
        borderTopLeftRadius: 16,
        borderTopRightRadius: 16,
      }}
      backgroundStyle={{
        backgroundColor: appTheme.colors?.background?.disabled,
      }}
    >
      <Text className="text-[18px] font-medium text-text1 mx-4 mt-2 mb-4 text-center">{props.title}</Text>
      <BottomSheetFlashList
        data={props.options}
        renderItem={renderItem}
        ItemSeparatorComponent={ItemSeparatorComponent}
        keyExtractor={(item, index) => index.toString()}
      />
    </BottomSheetModal>
  );
});

export default React.memo(SingleSelectBottomSheet);

const ItemSeparatorComponent = React.memo(() => {
  return <View className="mx-4 h-[1px] bg-line1" />;
});
